package com.stark.commons.spring.web.boot.config;

import java.util.Arrays;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsConfigurationSource;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.reactive.config.WebFluxConfigurer;

import com.stark.commons.spring.web.boot.properties.WebProperties;
import com.stark.commons.spring.web.boot.properties.WebProperties.CorsProperties;

import lombok.extern.slf4j.Slf4j;

/**
 * Web Flux 自动化配置。
 * @author Ben
 * @since 1.0.0
 * @version 1.0.0
 */
@Configuration
@ConditionalOnWebApplication(type = Type.REACTIVE)
@EnableConfigurationProperties(WebProperties.class)
@Slf4j
public class WebFluxAutoConfig implements WebFluxConfigurer {
	
	@Autowired
	private WebProperties webProperties;
	
	@Bean
	@ConditionalOnProperty(prefix = "web.cors", name = "enabled", havingValue = "true")
	public CorsConfigurationSource corsConfigurationSource() {
		CorsProperties corsProperties = webProperties.getCors();
		CorsConfiguration conf = new CorsConfiguration();
		conf.setAllowedOrigins(Arrays.asList(corsProperties.getAllowedOrigins().split(",")));
		conf.setAllowedMethods(Arrays.asList(corsProperties.getAllowedMethods().split(",")));
		conf.setAllowedHeaders(Arrays.asList(corsProperties.getAllowedHeaders().split(",")));
		conf.setAllowCredentials(corsProperties.isAllowCredentials());
		conf.setMaxAge(corsProperties.getMaxAge());
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		source.registerCorsConfiguration(corsProperties.getPathPattern(), conf);
		log.warn("\n-->web.cors.enabled=true, 配置跨域:"
				+ "\n   allowedOrigins=" + corsProperties.getAllowedOrigins()
				+ "\n   allowedMethods=" + corsProperties.getAllowedMethods()
				+ "\n   allowedHeaders=" + corsProperties.getAllowedHeaders()
				+ "\n   allowCredentials=" + corsProperties.isAllowCredentials()
				+ "\n   maxAge=" + corsProperties.getMaxAge());
		return source;
	}
	
}
